package fun.codedesign.principle.advice151.a016;

import javax.script.*;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;

/**
 * jvm越来越支持符合规范的脚本语言，因为简单，所以可以用脚本语言来写易变业务
 * model.js 脚本
 * function formula(var1, var2){return var1+var2 * factor;}
 * 改变脚本重新运行就可以，这样某些业务就不需要停止jvm来更新，只要更新脚本就可以了。
 */
public class ScriptingForJava {

    public static void main(String[] args) throws FileNotFoundException, ScriptException, NoSuchMethodException {
        // 获得一个javascript的执行引擎
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript");
        // 建立上下文变量
        Bindings binding = engine.createBindings();
        binding.put("factor", "1");
        // 绑定上下文,作用域是当前引擎范围
        engine.setBindings(binding, ScriptContext.ENGINE_SCOPE);
        try(Scanner sc = new Scanner(System.in)){
            while (sc.hasNextInt()) {
                int first = sc.nextInt();
                int second = sc.nextInt();
                System.out.println("输入参数是:" + first + "," + second);
                // 执行js代码
                engine.eval(new FileReader("D://model.js"));
                // 是否可调用方法
                if (engine instanceof Invocable) {
                    Invocable in = (Invocable) engine;
                    Double result = (Double) in.invokeFunction("formula", first, second);
                    System.out.println("运算结果是:" + result.intValue());
                }
            }
        }
    }
}
